import { useEffect, useState, useImperativeHandle, forwardRef } from 'react';
import { connect } from 'umi';
import * as echarts from 'echarts';
import { Modal, Select, Radio, Message } from 'antd';
import { configModal } from '@/assets';
import { HttpCode } from '#/utils/contacts.js';
import { NumberSub } from '@/utils';

import styles from './index.less';
import { getCssVariableValue } from '@/utils/utils';
import { TRMessage } from '#/components';
import {
  fetchForceForecastDatasourceList,
  fetchForceForecastChartData,
  globalForceDatasourceConfig,
  saveForecastVersion,
  getHuiNenForecastVersion,
  getHuiNenForecastData,
} from '@/pages/Tianji/DayRollingTradeStrategy/services';

const { Option } = Select;

function PowerForecastModal(
  {
    menuCode,
    tradeSeqId,
    stationId,
    stations,
    hourOrderList,
    tradeSeqList,
    echartsHourOrder,
    forecastDate,
    forecastPowerV,
    tableLimitPower,
    dispatch,
  },
  ref,
) {
  useImperativeHandle(ref, () => ({
    initHandle,
  }));

  const [showModal, setShowModal] = useState(false),
    // 预测源列表
    [sourceList, setSourceList] = useState([]),
    // 日期版本列表
    [dateList, setDateList] = useState([]),
    // 选中的数据源id
    [selectedSourceId, setSelectedSourceId] = useState(
      stations?.[0]?.value ? [stations[0].value] : [],
    ),
    // 选中的数据源日期版本
    [selectedSourceDate, setSelectedSourceDate] = useState(),
    [checked, setChecked] = useState(false),
    [chartDomIns, setChartDomIns] = useState(null);

  /**
   * 当数据源id或者日期版本发生改变时，获取数据源图形数据
   */
  useEffect(() => {
    if (showModal && selectedSourceDate) {
      fetchForceForecastChartDataAsync();
    }
  }, [showModal, selectedSourceDate]);

  const initHandle = (value) => {
    setSelectedSourceId(value ? [value] : []);
    setShowModal(true);
    // 调用接口获取预测源列表
    fetchForceForecastDatasourceListAsync();
  };

  // 获取出力预测数据源列表
  const fetchForceForecastDatasourceListAsync = async () => {
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const params = {
      marketId: 'PHBSX',
      stationId,
      date: forecastDate,
    };
    const res = await getHuiNenForecastVersion(params);
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      let datasourceList = res?.data || [];
      // setSourceList(datasourceList);
      setDateList(datasourceList || []);
      setSelectedSourceDate(
        selectedSourceDate ? selectedSourceDate : res.data.length > 0 ? forecastPowerV : null,
      );
    } else {
      Message.error(res.message || '获取出力预测数据源列表失败');
    }
  };

  // 获取出力预测数据源图表数据
  const fetchForceForecastChartDataAsync = async () => {
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const params = {
      date: forecastDate,
      marketId: 'PHBSX',
      stationId,
      version: selectedSourceDate,
    };
    const res = await getHuiNenForecastData(params);
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      let data = res?.data;
      initEchart(data?.xAxisData || [], data?.yAxisData?.map((item) => item.toFixed(3)) || []);
    } else {
      Message.error(res.message || '获取出力预测数据源echarts图数据失败');
    }
  };

  const changeSourceId = (values) => {
    setSelectedSourceId(values);
  };

  const initEchart = (xAxisData, yAxisData) => {
    chartDomIns && chartDomIns.dispose();

    var chartDom = document.getElementById('echart');
    var myChart = echarts.init(chartDom);
    var option = {
      color: ['#5E92F6'],
      grid: {
        left: '5%',
        right: '15',
        top: '30',
        bottom: '30',
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: '#161A1D',
        borderColor: 'transparent',
        textStyle: {
          color: '#A7A8A9',
        },
        formatter: (params) => {
          let str = `
          ${tradeSeqList
            .filter((item) => item.tradeSequenceId === tradeSeqId)[0]
            .forecastDate.replaceAll('-', '')} ${params[0].name}
           <br />
           ${params[0].marker} 出力预测 ${parseFloat(params[0].data).toFixed(3)}MWh
          `;
          return str;
        },
      },
      xAxis: {
        type: 'category',
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        data: xAxisData,
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisPointer: {
          lineStyle: {
            color: getCssVariableValue('--chart-font-color'),
            type: 'solid',
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisTick: {
          alignWithLabel: true,
        },
      },
      yAxis: {
        type: 'value',
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        // scale: true,
        axisLine: {
          show: false,
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
      },
      series: [
        {
          data: yAxisData,
          type: 'line',
          smooth: true,
          symbol: 'none',
        },
      ],
    };
    myChart.setOption(option);
    setChartDomIns(myChart);
  };
  const updateTableData = (resData) => {
    let hourOrderListNew = JSON.parse(JSON.stringify(hourOrderList));

    resData.forEach((item) => {
      const { timeOrder, forecastPower } = item;
      const index = timeOrder - 1;

      if (index >= 0 && index < hourOrderListNew.length) {
        const record = hourOrderListNew[index];

        // 1. 更新预测出力
        record.forecastPower = forecastPower;

        // 2. 计算修正预测出力
        let modifiedPower = 0;
        try {
          switch (tableLimitPower) {
            case '1':
              modifiedPower = NumberSub(forecastPower - (record.limitQuantity || 0));
              break;
            case '2':
              modifiedPower = NumberSub(forecastPower * (1 - (record.limitQuantity || 0)));
              break;
            default:
              modifiedPower = forecastPower;
          }
          record.revisedForecastPower = modifiedPower;

          // 3. 计算预计回收电量
          let recycleQuantity;
          if (modifiedPower > record.stationCapacity * 0.04) {
            recycleQuantity = Math.min(
              record.baseQuantityRation * modifiedPower +
                record.contractQuantity -
                modifiedPower * 3,
              record.contractQuantity,
            );
          } else {
            recycleQuantity = Math.min(
              record.baseQuantityRation * modifiedPower +
                record.contractQuantity -
                record.stationCapacity * 0.12,
              record.contractQuantity,
            );
          }
          record.expectedRecycleQuantity = NumberSub(recycleQuantity);

          // 4. 更新预计回收电费
          const recycleIncome = recycleQuantity * (record.recyclePrice - record.forecastPrice);
          record.recycleIncome = NumberSub(recycleIncome);
        } catch (err) {}
      }
    });

    dispatch({
      type: 'dayRollingTradeStragety/setHourOrderList',
      payload: hourOrderListNew,
    });
  };
  /*  const updateTableData = (resData) => {
    let hourOrderListNew = JSON.parse(JSON.stringify(hourOrderList));
    resData.forEach((item) => {
      const { timeOrder, forecastPower } = item;
      const index = timeOrder - 1;
      if (index >= 0 && index < hourOrderListNew.length) {
        hourOrderListNew[index] = {
          ...hourOrderListNew[index],
          forecastPower,
        };
      }
    });

    dispatch({
      type: 'dayRollingTradeStragety/setHourOrderList',
      payload: hourOrderListNew,
    });
  }; */
  /**
   * 设置出力预测数据源保存
   */
  const globalForceDatasourceConfigAsync = async () => {
    const params = {
      forecastType: '1',
      stationId,
      stationIds: selectedSourceId,
      tradeSequenceId: tradeSeqId,
      version: selectedSourceDate,
      date: forecastDate,
    };
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const res = await saveForecastVersion(params);
    dispatch({
      type: 'dayRollingTradeStragety/setForecastPowerV',
      payload: selectedSourceDate,
    });
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      setShowModal(false);
      updateTableData(res.data);
      TRMessage.success('设置成功');
      dispatch({
        type: 'dayRollingTradeStragety/setVersion1',
        payload: params.version,
      });
    } else {
      Message.error(res.message || '设置出力预测数据源失败');
    }
  };

  return (
    <Modal
      className={styles.powerForecastModal}
      centered={true}
      getContainer={false}
      title={
        <div className={styles.modalTitle}>
          <img src={configModal} />
          <span className={styles.text}>预测出力设置</span>
        </div>
      }
      visible={showModal}
      okText="提交"
      onCancel={() => {
        setShowModal(false);
        setSelectedSourceId(stations?.[0]?.value || null);
        setSelectedSourceDate(null);
      }}
      onOk={globalForceDatasourceConfigAsync}
    >
      <div className={styles.operate}>
        <div className={styles.setSource}>
          {/* <Select style={{ width: 170 }} value={selectedSourceId} onChange={changeSourceId}>
            {sourceList.map((item) => {
              return (
                <Option value={item.id} key={item.id}>
                  {item.name}
                </Option>
              );
            })}
          </Select> */}
          <Select
            className={styles.select}
            value={selectedSourceDate}
            onChange={(value) => {
              setSelectedSourceDate(value);
            }}
          >
            {dateList.map((item) => {
              return (
                <Option value={item} key={item}>
                  {item.replaceAll('-', '')}预测
                </Option>
              );
            })}
          </Select>
        </div>

        <Select
          mode="multiple"
          style={{ width: 170 }}
          value={selectedSourceId}
          onChange={changeSourceId}
          maxTagCount={1}
          maxTagTextLength={3}
        >
          {stations.map((item) => {
            return (
              <Option value={item.value} key={item.value}>
                {item.label}
              </Option>
            );
          })}
        </Select>
        {/* <Radio
          className={styles.setAll}
          checked={checked}
          onClick={() => {
            setChecked(!checked);
          }}
        >
          对全部交易单元生效
        </Radio> */}
      </div>
      <div id="echart" className={styles.echartsLine}>
        {''}
      </div>
    </Modal>
  );
}

export default connect(
  ({ dayRollingTradeStragety, global }) => ({
    menuCode: global.configure.menuCode,
    tradeSeqId: dayRollingTradeStragety.tradeSeqId,
    stationId: dayRollingTradeStragety.stationId,
    stations: dayRollingTradeStragety.stations,
    hourOrderList: dayRollingTradeStragety.hourOrderList,
    tradeSeqList: dayRollingTradeStragety.tradeSeqList,
    echartsHourOrder: dayRollingTradeStragety.echartsHourOrder,
    forecastDate: dayRollingTradeStragety.forecastDate,
    forecastPowerV: dayRollingTradeStragety.forecastPowerV,
    tableLimitPower: dayRollingTradeStragety.tableLimitPower,
  }),
  null,
  null,
  { forwardRef: true },
)(forwardRef(PowerForecastModal));
